﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NexTrackDesktop.MainService;
using System.Net;
using NexTrackDesktop.Media;
using System.Threading;

namespace NexTrackDesktop.NexTrack
{
    //Test Class for mocking some web server behavior.
    class MainServiceMock : MainServiceAdapter
    {

        public override void AddSong(Song song)
        {
            song.SongID = Guid.NewGuid().ToString();
            songs.Add(song);
        }

        public override string CreateParty(string description, string access_code, int voteLimit, int voteReplen)
        {
            ThreadStart ts = new ThreadStart(() =>
            {
                Random r = new Random();
                while(true)
                {
                    Thread.Sleep(r.Next(100,10000));

                    lock (this)
                    {
                        foreach (var item in queue)
                        {
                            item.UpVotes += r.Next(0, item.UpVotes / 2 + 2);
                            item.DownVotes += r.Next(0, item.UpVotes / 2 + 2);
                        }
                    }
                }
            });
            Thread t = new Thread(ts);
            t.IsBackground = true;
            t.Start();

            return Guid.NewGuid().ToString();
        }

        Song nowPlaying;

        public override Song GetNowPlaying()
        {
            return nowPlaying;
        }

        public override List<QueueItem> GetQueue()
        {
            return new List<QueueItem>(queue);
        }

        public override void RemoveSong(Song song)
        {
            songs.RemoveAll(s => s.SongID == song.SongID);
        }

        

        public override void UpdateNowPlaying(Song song)
        {
            lock (this)
            {
                //Shuffle songs.
                Random r = new Random();
                var shuffled = songs.OrderBy(x => r.NextDouble());

                if (queue.Count == 0)
                {
                    queue.Clear();
                    var it = shuffled.GetEnumerator();

                    for (int i = 0; i < Math.Min(20, shuffled.Count() * 0.7); i++)
                    {
                        it.MoveNext();
                        queue.Add(new QueueItem(it.Current) { UpVotes = i });
                    }
                }

                QueueItem dequeued = queue.FirstOrDefault(qi => qi.Song.SongID == song.SongID);
                if (dequeued != null)
                {
                    queue.Remove(dequeued);
                    Song enqueued = shuffled.First();
                    queue.Add(new QueueItem(enqueued) { UpVotes = r.Next(0, 30) });
                }

                nowPlaying = song;
            }
        }
    }
}
